#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：api_auto_upgrade 
@File    ：baiduOcrAccessToken.py
@IDE     ：PyCharm 
@Author  ：future76
@Date    ：2024/5/24 15:37 
@Desc    ：
"""
import base64
import binascii
import os
import requests
from loguru import logger


def getCodeImg():
    """
    获取验证码
    :return: base64编码的图片
    """
    url = "http://gateway.test.csbilin.com/uaa/login/getCodeImg"
    resp = requests.request("post",url = url)
    img = resp.json().get("data").get("img")
    # 解码图片
    imgdata = base64.b64decode(resp.json().get("data").get("img"))
    # 将图片保存为文件
    with open("temp.jpg", 'wb') as f:
        f.write(imgdata)
    return img

def access_token():
    """
    获取 Access Token

    获取详情请点击
    https://ai.baidu.com/ai-doc/OCR/skruaza7j
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    payload = {
        'grant_type': 'client_credentials',    # 固定为 client_credentials；
        'client_id': '',  # 应用的 API Key, 比如
        'client_secret': '' # 应用的 Secret Key
    }
    resp = requests.request("post", url=url, data=payload)
    token = resp.json().get("access_token")
    return token

def is_base64_encoded(s: str) -> bool:
    try:
        # 尝试Base64解码
        base64.b64decode(s, validate=True)
        return True
    except (ValueError, binascii.Error) as e:
        # 解码失败，可能不是Base64编码
        logger.info(f"Base64解码失败: {e}")
        return False

def accurate_basic(token, img):
    """
    通用文字识别高精度版
    :return: 验证码图片内容
    """
    if is_base64_encoded(img):
        img = img
    elif os.path.exists(img):   # 检查是否看起来像文件路径并存在于文件系统中
        with open(img, "rb") as image_file:
            image_data = image_file.read()
        # 使用base64库编码二进制数据
        encoded_image = base64.b64encode(image_data)
        # 将编码后的bytes转换为字符串
        img = encoded_image.decode('utf-8')
    try:
        url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token={token}"
        payload = {
            "image": img
        }
        resp = requests.request("post",url=url, data=payload)
        words = resp.json().get("words_result")[0].get("words")
        print(words)
        print(resp.json())
        return words
    except:
        print("百度OCR无法识别")
        return None


def analysis_result(words):
    """
    验证码结果计算
    :return:
    """
    try:
        if words[2] in ["=", "≈", "~", "?"] or len(words) == 3:
            operator = "-"
            num2 = int(words[1])
            num1 = int(words[0])
        elif words[0] == "日":
            num1 = 6
            if words[2] == "日":
                num2 = 6
            else:
                num2 = int(words[2])
            operator = words[1]
        elif words[2] == "日":
            num1 = int(words[0])
            num2 = 6
            operator = words[1]
        elif words[0] in ["y", "Y"]:
            num1 = 7
            num2 = int(words[2])
            operator = words[1]
        elif words[2] in ["y", "Y"]:
            num1 = int(words[0])
            num2 = 7
            operator = words[1]
        elif words[0] == "g":
            num1 = 9
            if words[2] == "g":
                num2 = 9
            else:
                num2 = int(words[2])
            operator = words[1]
        elif words[2] == "g":
            num1 = int(words[0])
            num2 = 9
            operator = words[1]
        elif words[0] == "]":
            num1 = 1
            if words[2] == "]":
                num2 = 1
            else:
                num2 = int(words[2])
            operator = words[1]
        elif words[2] == "]":
            num1 = int(words[0])
            num2 = 1
            operator = words[1]
        elif words[0] == "d":
            num1 = 0
            if words[2] == "d":
                num2 = 0
            else:
                num2 = int(words[2])
            operator = words[1]
        elif words[2] == "d":
            num1 = int(words[0])
            num2 = 0
            operator = words[1]
        else:
            num1 = int(words[0])
            num2 = int(words[2])
            operator = words[1]
        print(num1, operator, num2)
        if operator == "+":
            result = num1 + num2
        elif operator in ["-", ".", ":"]:
            if num1 < num2 and num1 == 1:
                result = 7 - num2
            else:
                result = num1 - num2
        elif operator == "*":
            result = num1 * num2
        elif operator in ["/", "1", "("]:
            result = num1 // num2
            if num2 != 0:
                result = num1 // num2
            elif num1 < num2 and num1 == 1:
                result = 7 // num2
            else:
                logger.info('除数不能为0')
                result = None
        else:
            logger.info('无效的运算符')
            result = None
        return result
    except (ValueError, IndexError):
        logger.info('无法解析数字或运算符')
        return None
    except TypeError:
        logger.info('百度ocr无法识别')
        return None



if __name__ == '__main__':
    # 图片文件路径
    image_path = 'temp.jpg'

    words = accurate_basic(access_token(), getCodeImg())
    # words = accurate_basic(access_token(), image_path)
    print(analysis_result(words))
